﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Linq.Expressions;

namespace SqliteManager.SQLite3
{
    /// <summary>
    /// 数据库控制器
    /// </summary>
    public class Sqlite3DataBase
    {
        protected string _Path = "";
        protected SQLiteConnection _Connection;
        protected SQLiteCommand _Command;
        protected SQLiteDataReader _Reader;

        /// <summary>
        /// 数据库文件的存储路径
        /// </summary>
        public string Path
        {
            get
            {
                return _Path;
            }
        }

        /// <summary>
        /// 通过文件路径构造一个新的数据库控制器
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isAutoConnect">是否自动连接到数据库</param>
        public Sqlite3DataBase(string path,bool isAutoConnect = true)
        {
            _Path = path;
            if(isAutoConnect)
            {
                Connect();
            }
        }

        ~Sqlite3DataBase()
        {

            try
            {
                if (_Connection != null)
                {
                    _Connection.Close();
                }
                
            }catch(Exception e)
            {
                Logger.Log($"{GetType()}.~Dispose:{e.Message}");
            }finally
            {
                _Connection = null;
            }
        }

        /// <summary>
        /// 连接数据库
        /// </summary>
        public void Connect()
        {
            _Connection = new SQLiteConnection($"Data Source = {_Path};Version=3");
            _Connection.Open();
        }

        /// <summary>
        /// 执行命令
        /// </summary>
        /// <returns>The query.</returns>
        /// <param name="queryString">SQL命令字符串</param>
        public SQLiteDataReader ExecuteQuery(string queryString)
        {
            try
            {
                _Command = _Connection.CreateCommand();
                _Command.CommandText = queryString;
                _Reader = _Command.ExecuteReader();
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
            }
            return _Reader;
        }
    }
}
